#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h> /* superset of previous */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>

int main(void)
{
    // 1.创建UDP对象
    int udp_socket = socket(AF_INET, SOCK_DGRAM, 0);

    // 使套接字sockfd关联的地址在套接字关闭后立即释放
    int on = 1;
    setsockopt(udp_socket, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));  //开启端口复用功能 
    
    // 2.开启广播功能
    int flag = 1;
    int ret = setsockopt(udp_socket, SOL_SOCKET, SO_BROADCAST, &flag, sizeof(flag));
    if (ret < 0)
    {
        perror("开启广播失败\n");
        return -1;
    }
    else
    {
        printf("开启广播成功\n");
    }

    // 3.设置广播地址
    struct sockaddr_in addr;
    addr.sin_family      = AF_INET;
    addr.sin_port        = htons(8888);
    addr.sin_addr.s_addr = inet_addr("192.168.10.255"); // 广播地址


    // 4.发送数据
    char *msg = "hello,everbody";
    ret = sendto(udp_socket, msg, strlen(msg), 0, (struct sockaddr *)&addr, sizeof(addr));
    if (ret < 0)
    {
        perror("发送失败\n");
        return -1;
    }
    else
    {
        printf("发送广播数据成功 %d\n", ret);
    }
}